import { message } from 'antd';
import { routerRedux } from 'dva/router';
import { login, editPasswd } from '../services/login';
import { setAuthority } from '../../../utils/authority';
import { reloadAuthorized } from '../../../utils/Authorized';

export default {
  namespace: 'userLogin',

  // 状态机
  state: {
    loading: false,
    loading_modifyPassword: false,
  },

  // 发起网络请求
  effects: {
    *submit({ payload }, { call, put }) {
      let response = yield call(login, payload);
      if (!response.success) {
        message.error(response.msg);
        yield put({ type: 'changeStatus', status: false });
        return;
      }
      setAuthority(response, payload.userName);
      reloadAuthorized();

      const menu = response.menus;
      for (let i = 0; i < menu[0].children.length; i += 1) {
        const item = menu[0].children[i];
        if (item.name === '用户管理' && item.path === 'user') {
          menu[0].children[i].path = 'users';
          break;
        }
      }
      yield put({ type: 'saveToLocal', name: 'menu', data: response.menus });
      yield put({ type: 'changeStatus', status: false });
      yield put(routerRedux.push('/'));
    },
    *modifyPassword({ payload }, { call, put }) {
      const response = yield call(editPasswd, payload);
      if (response.success) {
        sessionStorage.setItem('antd-pro-authority', 'guest');
        reloadAuthorized();
        // yield put(routerRedux.push('/user/login'));
        message.success(response.msg);
        window.parent.document.location.reload();
      } else if (response.status === 1) message.error(response.msg);

      yield put({ type: 'callback_modifyPassword', response });
    },
  },

  // 回调处理
  reducers: {
    changeStatus(st, params) {
      const state = st;
      state.loading = params.status;
      return { ...state };
    },
    saveToLocal(state, params) {
      const data = JSON.stringify(params.data);
      localStorage.setItem(params.name, data);
      return { ...state };
    },
    callback_modifyPassword(st) {
      const state = st;
      state.loading_modifyPassword = false;
      return { ...state };
    },
  },
};
